import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, Dropdown, Popconfirm, message, Divider, Form, Select, Input, DatePicker} from "antd";
import MaintainPerson from '../../Form/MaintainPerson';
import StandardTable from '../../../components/StandardTable';
import Authorized from '../../../utils/Authorized';
import styles from '../../Pbulic.less';


const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ task, global,loading }) => ({
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  resdata: task.resdata,
  loading: task.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { pageSize } = this.state;
    const { pagesquery, dispatch} = this.props;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // // 养护人
    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });

    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }

  // componentWillReceiveProps(nextProps) {
  //   // 外层发起刷新数据请求
  //   if (nextProps.isReloadList === true && this.props.isReloadList === false) {
  //     const { pageSize } = this.state;
  //     this.getDataList({},pageSize,1);
  //     this.props.sotpReloadList();
  //   }
  // }

  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }
  }

  getDataList(params,pageSize,currentPage) {
    const { dispatch } = this.props;
    dispatch({
      type: 'task/fetch_task_history_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        maintenanceInfo:undefined,
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      planCode:undefined,
      planName:undefined,
      taskCode:undefined,
      taskName:undefined,
      beginTime:undefined,
      maintenanceInfo:{ maintenanceId:0, userId:0 },
    });
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.taskId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.maintenanceInfo && fieldsValue.maintenanceInfo.maintenanceId!==0){
        fieldsValue.maintenanceId = fieldsValue.maintenanceInfo.maintenanceId;
      }
      if(fieldsValue.maintenanceInfo && fieldsValue.maintenanceInfo.userId!==0){
        fieldsValue.maintainManId = fieldsValue.maintenanceInfo.userId;
      }

      if(fieldsValue.beginTime){
        fieldsValue.beginTime = [fieldsValue.beginTime[0].unix() * 1000,fieldsValue.beginTime[1].unix() * 1000]
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };



  // 链接跳转-------------------
  handleLink = (action,detailInfoId) =>{
    const { dispatch } = this.props;
    const { formValues, currentPage} = this.state;
    let linkpath;
    switch (action) {
      case 'info':
        linkpath = `/maintain/historyrecords/detail/info/${detailInfoId}`;
        break;
      default:
        break;
    }
    router.push({ pathname:`${linkpath}`,  query: { ...formValues, currentPage} });
  }


  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource, pagesquery } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="养护单号">
              {getFieldDecorator('taskCode',{
                initialValue: pagesquery && pagesquery.taskCode ? pagesquery.taskCode : undefined,
              })(<Input placeholder="请输入养护单号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="任务名称">
              {getFieldDecorator('taskName',{
                initialValue: pagesquery && pagesquery.taskName ? pagesquery.taskName : undefined,
              })(<Input placeholder="请输入任务名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="计划编号">
              {getFieldDecorator('planCode',{
                initialValue: pagesquery && pagesquery.planCode ? pagesquery.planCode : undefined,
              })(<Input placeholder="请输入计划单号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="计划名称">
              {getFieldDecorator('planName',{
                initialValue: pagesquery && pagesquery.planName ? pagesquery.planName : undefined,
              })(<Input placeholder="请输入计划名称" />)}
            </FormItem>
          </Col>


        </Row>



        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('beginTime',{
                initialValue: pagesquery && pagesquery.beginTime ? pagesquery.beginTime : undefined,
              })(
                <RangePicker
                  // showTime={{ format: 'HH:mm:ss' }}
                  format="YYYY-MM-DD"
                  placeholder={['开始时间', '结束时间']}
                />
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <FormItem  label="维保单位">
              {getFieldDecorator("maintenanceInfo", {
                initialValue: pagesquery && pagesquery.maintenanceInfo ? pagesquery.maintenanceInfo : { maintenanceId:0, userId:0 },
              })(
                <MaintainPerson
                  placeholder={"请选择养护人"}
                  maintainData={selectSource.maintenance}
                  personnelData={selectSource.maintenman}
                  onChange={this.handleSearchMaintain}
                />
              )}
            </FormItem>
          </Col>


          <Col md={6} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries } = this.props;
    const { selectedRows } = this.state;
    const repairStatus = dictionaries.repairStatus && dictionaries.repairStatus.length>1
      ? dictionaries.repairStatus.map(item=>item.label)
      :[];

    const columns = [
      {
        title: '养护单号',
        dataIndex: 'taskCode',
      },
      {
        title: '任务名称',
        dataIndex: 'taskName',
      },
      {
        title: '计划编号',
        dataIndex: 'planCode',
      },
      {
        title: '计划名称',
        dataIndex: 'planName',
      },
      {
        title: '维保单位',
        dataIndex: 'maintenanceName',
      },
      {
        title: '养护人',
        dataIndex: 'maintainManName',
      },
      {
        title: '开始时间',
        dataIndex: 'beginTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '完成时间',
        dataIndex: 'signTime',
        render: text => moment(text).format("YYYY-MM-DD HH:mm")
      },
      {
        title: '操作',
        width: 150,
        fixed:'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10132'} >
              <a onClick={() => this.handleLink('info',row.taskId)}>详情</a>
            </Authorized>
          </Fragment>
        ),
      },
    ];


    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="taskId"
            scroll={{ x: 1500 }}
            loading={loading.reslist}
            data={resdata}
            columns={columns}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
